//
//  NetworkHelper.swift
//  WeatherDemo2
//
//  Created by 王巍 on 16/5/12.
//  Copyright © 2016年 ww. All rights reserved.
//


import Just

// 定义枚举类型
enum NetworkHelper {
    
    case WeeklyWeather(cityid: String)

    // static 成为类方法
    static var params = [
        "app":"weather.future",
        "appkey":"10003",
        "sign":"b59bc3ef6191eb9f747dd4e83c99f2a4",
        "format":"json"
    ]
    
    static let baseUrl = "http://api.k780.com:88";
    
    
    // 使用闭包 执行异步处理完成后操作
    func getWeather(completion: ([Result]?, String?) -> Void) {
        
        var error: String?
        var results:[Result]?
        
        switch self {
        case .WeeklyWeather(cityid: let weaid):
            NetworkHelper.params["weaid"] = weaid
            Just.get(NetworkHelper.baseUrl, params: NetworkHelper.params, asyncCompletionHandler: { (r) in
                if r.ok {
                    guard let jsonDict = r.json as? NSDictionary else {
                        error = "不是一个json字符串"
                        return
                    }
                    
                    guard let success = jsonDict["success"] where success as? String == "1" else{
                        error = "返回数据格式不对，或者授权错误"
                        return
                    }
                    let weather = Weather(fromDictionary: jsonDict)
                    results = weather.result
                    
                    
                }else{
                    error = "服务器出错"
                }
                
                completion(results, error)
            })
            
        }
    }
    
}